package com.wait.onlinepicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wait.onlinepicture.annotation.AuthCheck;
import com.wait.onlinepicture.common.DeleteRequest;
import com.wait.onlinepicture.constant.UserConstant;
import com.wait.onlinepicture.exception.BusinessException;
import com.wait.onlinepicture.manager.FileManager;
import com.wait.onlinepicture.manager.auth.annotation.SaSpaceCheckPermission;
import com.wait.onlinepicture.manager.auth.model.SpaceUserPermissionConstant;
import com.wait.onlinepicture.model.dto.file.UploadPictureResult;
import com.wait.onlinepicture.model.dto.picture.PictureUploadRequest;
import com.wait.onlinepicture.model.dto.user.*;
import com.wait.onlinepicture.model.entity.User;
import com.wait.onlinepicture.model.vo.picture.PictureVO;
import com.wait.onlinepicture.model.vo.user.LoginUserVO;
import com.wait.onlinepicture.common.BaseResponse;
import com.wait.onlinepicture.common.ResultUtils;
import com.wait.onlinepicture.exception.ErrorCode;
import com.wait.onlinepicture.exception.ThrowUtils;
import com.wait.onlinepicture.model.vo.user.UserVO;
import com.wait.onlinepicture.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.core.SpringVersion;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author with葡萄成熟时
 * @version 1.0
 * 用户相关接口
 */
@RestController
@RequestMapping("/user")

public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private FileManager fileManager;

    /**
     * description 用户注册接口
     * author Wait葡萄成熟时
     * date 下午9:26 2025/3/10
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        Long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * description 用户登录接口
     * author Wait葡萄成熟时
     * date 下午9:26 2025/3/10
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * description 从请求头获取当前登录用户接口
     * author Wait葡萄成熟时
     * date 下午9:46 2025/3/10
     */
    @ApiOperation("从请求头获取当前登录用户")
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    /**
     * description 用户登录注销接口
     * author Wait葡萄成熟时
     * date 下午9:46 2025/3/10
     */
    @ApiOperation("用户登录注销")
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }


    /**
     * description 创建用户
     * author Wait葡萄成熟时
     * date 上午12:16 2025/3/11
     */
    @ApiOperation("创建用户")
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * description 根据 id 获取用户（仅管理员）
     * author Wait葡萄成熟时
     * date 上午12:16 2025/3/11
     */
    @ApiOperation("根据 id 获取用户（仅管理员）")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * description 根据 id 获取包装类
     * author Wait葡萄成熟时
     * date 上午12:16 2025/3/11
     */
    @ApiOperation("根据 id 获取包装类")
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * description 删除用户
     * author Wait葡萄成熟时
     * date 上午12:16 2025/3/11
     */
    @ApiOperation("删除用户")
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * description 更新用户
     * author Wait葡萄成熟时
     * date 上午12:16 2025/3/11
     */
    @ApiOperation("更新用户")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * description 给用户修改
     * author Wait葡萄成熟时
     */
    @ApiOperation("更新用户")
    // @PostMapping注解表示该方法是一个POST请求，请求路径为/edit
    @PostMapping("/edit")
    // 返回一个BaseResponse<Boolean>类型的数据
    public BaseResponse<Boolean> editUser(@RequestBody UserEditRequest userEditRequest) {
        // 判断userEditRequest是否为空，或者userEditRequest的id是否为空
        if (userEditRequest == null || userEditRequest.getId() == null) {
            // 如果为空，抛出参数错误异常
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建一个User对象
        User user = new User();

        // 将userEditRequest中的属性值复制到user对象中
        BeanUtils.copyProperties(userEditRequest, user);
        // 调用userService的updateById方法更新用户信息
        boolean result = userService.updateById(user);
        // 如果更新失败，抛出操作错误异常
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回更新成功的响应
        return ResultUtils.success(true);
    }
    /**
     * description 分页获取用户封装列表（仅管理员）
     * author Wait葡萄成熟时
     * date 上午12:16 2025/3/11
     */
    @ApiOperation("分页获取用户封装列表（仅管理员）")
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        //设置分页信息
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        // 把List<User>转换List<UserVO>
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        //把List<UserVO>存入userVOPage
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

    /**
     * description 上传头像
     * author Wait葡萄成熟时
     */
    @ApiOperation("上传头像")
    @PostMapping("/upload")
    /*@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)*/
    public BaseResponse<UploadPictureResult> uploadPictureUser(
            @RequestPart("file") MultipartFile multipartFile,
            HttpServletRequest request) {

      String  uploadPathPrefix = String.format("PictureUser/%s", System.currentTimeMillis());
        UploadPictureResult uploadPictureResult = fileManager.uploadPicture(multipartFile, uploadPathPrefix);

        return ResultUtils.success(uploadPictureResult);
    }
}

